package com.sumer.brain.common.security.filter;

import com.alibaba.fastjson2.JSON;
import com.sumer.brain.common.config.JwtProperties;
import com.sumer.brain.common.constant.SystemConstant;
import com.sumer.brain.common.enums.HttpStatus;
import com.sumer.brain.common.model.R;
import com.sumer.brain.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static com.sumer.brain.common.config.WebSecurityConfig.IGNORE_STATIC_URI;
import static com.sumer.brain.common.config.WebSecurityConfig.IGNORE_URI;

@RequiredArgsConstructor
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (IGNORE_URI.contains(uri)) {
            filterChain.doFilter(request, response);
            return;
        }
        //静态资源放行
        for (String ignore : IGNORE_STATIC_URI) {
            if (uri.startsWith(ignore)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        // 解析token
        String token = request.getHeader(SystemConstant.ACCESS_TOKEN);
        if (!StringUtils.hasText(token)) {
            R<Object> result = R.build(HttpStatus.UNAUTHORIZED.getCode(), "token不能为空", null);
            response.setContentType(SystemConstant.CONTENT_TYPE);
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }
        token = token.replace(SystemConstant.TOKEN_PREFIX, "");
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(claims.get("name"), null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (Exception e) {
            R<Object> result = R.build(HttpStatus.UNAUTHORIZED.getCode(), "token无效", null);
            response.setContentType(SystemConstant.CONTENT_TYPE);
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }
        filterChain.doFilter(request, response);
    }
}
